"""
用户认证工具函数
"""
import re
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string


def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def get_user_agent(request):
    """获取用户代理信息"""
    return request.META.get('HTTP_USER_AGENT', '')


def validate_phone(phone):
    """验证手机号格式"""
    pattern = r'^1[3-9]\d{9}$'
    return re.match(pattern, phone) is not None


def send_notification_email(user, subject, template_name, context=None):
    """发送通知邮件"""
    if not user.email:
        return False
    
    if context is None:
        context = {}
    
    context.update({
        'user': user,
        'site_name': '鸥鹏超级面试官'
    })
    
    try:
        html_message = render_to_string(template_name, context)
        send_mail(
            subject=subject,
            message='',
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[user.email],
            html_message=html_message,
            fail_silently=False
        )
        return True
    except Exception as e:
        print(f"发送邮件失败: {e}")
        return False


def generate_username(first_name, last_name, student_id=None):
    """生成用户名"""
    if student_id:
        return student_id
    
    base_username = f"{first_name}{last_name}".lower()
    username = base_username
    counter = 1
    
    from .models import User
    while User.objects.filter(username=username).exists():
        username = f"{base_username}{counter}"
        counter += 1
    
    return username


def check_password_strength(password):
    """检查密码强度"""
    if len(password) < 8:
        return False, "密码长度至少8位"
    
    if not re.search(r'[A-Za-z]', password):
        return False, "密码必须包含字母"
    
    if not re.search(r'\d', password):
        return False, "密码必须包含数字"
    
    return True, "密码强度合格"
